import express from "express";
import {SSEServerTransport} from "@modelcontextprotocol/sdk/server/sse.js";
import {McpServer, ResourceTemplate} from "@modelcontextprotocol/sdk/server/mcp.js";

// 基于 express 实现 sse 传输
const app = express();
const mcpServer = new McpServer({
    name: "example-server",
    version: "1.0.0"
});
let transport: SSEServerTransport | null = null;
app.get("/sse", async (req, res) => {
    console.log(req.body)
    transport = new SSEServerTransport("/messages", res);
    await mcpServer.connect(transport);
});
app.post("/messages", async (req, res) => {
    if (transport) {
        await transport.handlePostMessage(req, res);
    }
});
app.listen(3000);

// 直接资源
let appConfig = "一些配置内容"
mcpServer.resource(
    "config",
    "config://app",
    async (uri) => ({
        contents: [{
            uri: uri.href,
            text: appConfig
        }]
    })
);

// 模板资源
const userProfileResources = [{
    uri: 'users://1001/profile',
    name: 'user-1001-profile'
}]
// 注册模板资源
mcpServer.resource(
    "user-profile",
    new ResourceTemplate("users://{userId}/profile", {
        list: async () => ({
            resources: userProfileResources
        })
    }),
    async (uri, {userId}) => ({
        contents: [{
            uri: uri.href,
            text: `用户 ${userId} 的个性化配置`
        }]
    })
);

// 模拟资源动态更新
setInterval(async () => {
    // 修改配置内容
    appConfig = `一些配置内容${new Date().getTime()}`

    // 随机增加一个用户配置
    const userId = new Date().getTime()
    userProfileResources.push({
        uri: `users://${userId}/profile`,
        name: `user-${userId}-profile`
    })

    if (transport) {
        // 通知客户端资源列表更新
        await mcpServer.server.notification({method: "notifications/resources/list_changed"});
        // 通知客户端资源内容更新
        await mcpServer.server.notification({method: "notifications/resources/updated", params: {uri: "config://app"}});
    }
}, 5000)

